# -*- coding: utf-8 -*-

# Create your views here.

from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.shortcuts import render_to_response
from forum.models import Autor,Temat,Odpowiedz,Adress
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
import datetime
from django.http import Http404
import re
from forum.forms import NowyProjekt, EdycjaProjekt, NowyTemat, NowaOdpowiedz, PrzypHaslo
from settings import FONTS_DIR, MEDIA_DIR
import StringIO
from django.core.mail import send_mail


from PIL import Image, ImageDraw, ImageFont

import random
INK = "red", "blue", "green"
KOD = 'A','B','C','D','E','F','G','H','I','J','L'

def image(request):

	# ... create/load image here ...
	image = Image.new("RGB", (100, 50), random.choice(INK))
	
	# use a bitmap font
	font = ImageFont.truetype( FONTS_DIR + "a.ttf", 30)
	#font = ImageFont.truetype("/www/virtual/rubikon.itl.pl/htdocs/nowy/forum/a.ttf", 30)


	kawka = random.choice(KOD) +random.choice(KOD) +random.choice(KOD)
	request.session['kod'] = kawka
	

	draw = ImageDraw.Draw(image)
	draw.line((0, 0) + image.size, fill=128)
	draw.line((0, image.size[1], image.size[0], 0), fill=128)
	draw.text((0,0), kawka, font=font)
	del draw
	
	# serialize to HTTP response
	response = HttpResponse(mimetype="image/png")
	image.save(response, "PNG")
	return response

def profil(request, profil):

	a = Autor.objects.select_related('user').filter(user__isnull=False).get(pk=profil)
	tematy = a.temat_set.all().order_by('-data_pub')[0:10]
	odp = a.odpowiedz_set.all().order_by('-data_pub')[0:10]
	return render_to_response('profil.html', {'a':a, 'tem':tematy, 'odp':odp, 'req':request})

def emolista(request):
	return render_to_response('emotki.html', {'req':request})

def index(request, podstrona):
	il = 30
	start_ind = int(podstrona)*il
	end_ind = int(start_ind) + il
	
	#q=Temat.objects.extra(select={'hehe':"SELECT max(data_pub) FROM forum_odpowiedz WHERE temat_id = forum_temat.id"})
	#m = q.extra(order_by=['-hehe'])
	#tematy = m[start_ind:end_ind]
	
	#tematy = Temat.objects.order_by('-data_up')[start_ind:end_ind]
	tematy = Temat.objects.extra(select={'odp':'SELECT COUNT(*) FROM forum_odpowiedz WHERE forum_odpowiedz.temat_id=forum_temat.id'}).order_by('-data_up')[start_ind:end_ind]
	ile_podstron = range(Temat.objects.all().count()/il+1)
	return render_to_response('index.html', {'tematy':tematy, 'podstrony':ile_podstron, 'req':request})
	
def watek(request, temat, podstrona):
	il = 20
	start_ind = int(podstrona)*il
	end_ind = int(start_ind) + il
	odpowiedzi = Temat.objects.get(pk=temat).odpowiedz_set.select_related(depth=1).order_by('data_pub')[start_ind:end_ind]
	ile_podstron = range(Temat.objects.get(pk=temat).odpowiedz_set.all().count()/il +1)
	temat = Temat.objects.get(pk=temat)
	loged = request.user.is_authenticated()
	return render_to_response('watek.html', {'odpowiedzi':odpowiedzi, 'temat':temat, 'podstrony':ile_podstron, 'req':request})
	
	
def odpowiedz2(request, temat, cytat):
	if request.method == 'POST':
	
		form = NowaOdpowiedz(request.POST)
		form.req = request
		if form.is_valid():
		
			#czy kodeLe z obrazka siE zgadza?
			if request.POST['kod'].upper() != request.session['kod']:
				tekst = u'Złe kodełe z obrazka i tyle. Próbujesz ponownie'
				return render_to_response('errorek.html',{'blad':tekst, 'req':request})

			#ile wpisow z tego adresu przez ostatnia minute?
			now = datetime.datetime.now()
			min=datetime.timedelta(minutes=1)
			if Adress.objects.filter(addres=request.META['REMOTE_ADDR'], data_wiz__gt=now-min).count() >= 4:
				tekst = u'W ciągu minuty mozez dodac jedynie 4 odpowiedzi'
				return render_to_response('errorek.html',{'blad':tekst, 'req':request})

			#czyz to nie jeste sraka?
			a = request.POST['tresc']
			if len(re.compile(u'\n').findall(a))*5>len(a) or len(re.compile(u'\n').findall(a))>50:
				tekst = u'Tutej nie srame'
				return render_to_response('errorek.html',{'blad':tekst, 'req':request})
				
			#obsluga tego calego bajzlu
			#obsluga autora
			if request.user.is_authenticated():
				#print 'raz'
				autor = request.user.get_profile()
			else:
				if  Autor.objects.filter(pseudo=request.POST["autor"]).filter(user__isnull=False).count()!=0:
					#print 'trzy'
					tekst = u'Nick jest już zajęty przez niebieskiego'
					return render_to_response('errorek.html',{'blad':tekst, 'req':request})	
				elif Autor.objects.filter(pseudo=request.POST['autor']).count()==0:
					#print 'dwa'
					autor = Autor(pseudo=request.POST['autor'])
					autor.save()
				else:
					#print 'cztery'
					autor = Autor.objects.filter(pseudo=request.POST["autor"])[0]
			request.session['pomarancza'] = autor.pseudo
					
			#obsluga adresu
			addres = Adress(addres=request.META['REMOTE_ADDR'], autor=autor,data_wiz=datetime.datetime.now())
			addres.save()
			
			temat = Temat.objects.get(pk=temat)
			temat.data_up = datetime.datetime.now()
			temat.save()
			odpowiedz = Odpowiedz(temat=temat, autor=autor, tresc=request.POST['tresc'], data_pub=datetime.datetime.now())
			odpowiedz.save()
			
			return HttpResponseRedirect(reverse('forum.views.index', args=(0,)))
	else:
		if request.session.has_key('pomarancza'):
			serek = request.session['pomarancza']
		else:
			serek = 'żywe gówno'
			
		if request.user.is_authenticated():
			serek = request.user
	
		if cytat == u'c':
			form = NowaOdpowiedz(initial={'autor':serek})
		else:
			odpowiedz = Odpowiedz.objects.get(pk=cytat)
			#print odpowiedz.tresc
			dupa = '[cytat autor="'+odpowiedz.autor.pseudo+'"]'+odpowiedz.tresc+'[/cytat]'
			form = NowaOdpowiedz(initial={'autor':serek, 'tresc':dupa})
		
	return render_to_response('odpowiedz.html', {'form':form, 'req':request, 'temat':temat})
	
	
	
def logowanie(request):
	username = request.POST['login']
	password = request.POST['haslo']
	user = authenticate(username=username, password=password)
	if user is not None:
		if user.is_active:
			login(request, user)
			# Redirect to a success page.
			return HttpResponseRedirect(reverse('forum.views.index', args=(0,)))
		else:
			# Return a 'disabled account' error message
			tekst = u'Konto zablokowane'
			return render_to_response('errorek.html',{'blad':tekst, 'req':request})	
	else:
		# Return an 'invalid login' error message.
		tekst = u'Złe logine, lub hasło'
		return render_to_response('errorek.html',{'blad':tekst, 'req':request})	
		
def wyloguj(request):
	logout(request)
	return HttpResponseRedirect(reverse('forum.views.index', args=(0,)))
	
def nowy_projekt(request):
	if request.method == 'POST':
	
		#czy kodełe z obrazka się zgadza?
		if request.POST['kod'].upper() != request.session['kod']:
			tekst = u'Złe kodełe z obrazka i tyle. Próbujesz ponownie'
			return render_to_response('errorek.html',{'blad':tekst})
		
		form = NowyProjekt(request.POST, request.FILES)
		if form.is_valid():
			
			#form.cleaned_data['pseudo']
			user = User.objects.create_user(form.cleaned_data['pseudo'], form.cleaned_data['email'], form.cleaned_data['haslo1'])
			user.save()
			autor = Autor(pseudo=form.cleaned_data['pseudo'], user=user, rank=0)
			autor.save()
			
			userek = authenticate(username=form.cleaned_data['pseudo'], password=form.cleaned_data['haslo1'])
			login(request, userek)
			
			
			f = request.FILES['avatar']
			destination = open(MEDIA_DIR+str(user.id), 'wb+')
			for chunk in f.chunks():
				destination.write(chunk)
			destination.close()
			
			#zmiana rozmiaru
			im = Image.open(MEDIA_DIR+str(user.id))
			im.thumbnail((100,150), Image.ANTIALIAS)
			im.save(MEDIA_DIR+str(user.id) + "_avt", im.format)
			#print "wsio ok"
			return HttpResponseRedirect(reverse('forum.views.index', args=(0,)))
	else:
		form = NowyProjekt()
		
	return render_to_response('form.html', {'form':form})
	
def edycja_projekt(request):
	if request.method == 'POST':
	
		
		form = EdycjaProjekt(request.POST, request.FILES)
		form.req = request
		if form.is_valid():
			#zmiana hasla
			if form.cleaned_data['haslo2'] != u'':
				request.user.set_password( form.cleaned_data['haslo2'] )
				request.user.save()		
 
		
			#zmiana stopki
			if form.cleaned_data['stopka'] != u'':
				autor = request.user.get_profile()
				autor.stopka = form.cleaned_data['stopka']
				autor.save()
		
			#zmiana pola pseudo
			if form.cleaned_data['pseudo'] != u'':
				autor = request.user.get_profile()
				autor.pseudo = form.cleaned_data['pseudo']
				autor.save()
				request.user.username = form.cleaned_data['pseudo']
				request.user.save()

				
			#zmiana pola email
			if form.cleaned_data['email'] != u'':
				request.user.email = form.cleaned_data['email']
				request.user.save()
			
			#zmiana avatara
			if form.cleaned_data['avatar'] != None:
				#form.cleaned_data['pseudo']
				user = request.user;
				#print user.id
				#print user.get_profile().user_id
			
				f = request.FILES['avatar']
				destination = open(MEDIA_DIR+str(user.id), 'wb+')
				for chunk in f.chunks():
					destination.write(chunk)
				destination.close()
			
				#zmiana rozmiaru
				im = Image.open(MEDIA_DIR+str(user.id))
				im.thumbnail((100,150), Image.ANTIALIAS)
				im.save(MEDIA_DIR+str(user.id) + "_avt", im.format)
				#print "wsio ok"
			return HttpResponseRedirect(reverse('forum.views.index', args=(0,)))
	else:
		form = EdycjaProjekt(initial={'pseudo':request.user,
										'email':request.user.email,
										'stopka':request.user.get_profile().stopka})
		
	return render_to_response('form_edycja.html', {'form':form, 'req':request})


def nowytemat2(request):
	if request.method == 'POST':
	
		form = NowyTemat(request.POST)
		form.req = request
		if form.is_valid():
		
			#czy kodełe z obrazka się zgadza?
			if request.POST['kod'].upper() != request.session['kod']:
				tekst = u'Złe kodełe z obrazka i tyle. Próbujesz ponownie'
				return render_to_response('errorek.html',{'blad':tekst, 'req':request})

			#ile wpisow z tego adresu przez ostatnia minute?
			now = datetime.datetime.now()
			min=datetime.timedelta(minutes=30)
			if Adress.objects.filter(addres=request.META['REMOTE_ADDR'], data_wiz__gt=now-min).count() >= 10:
				tekst = u'W ciągu 30 minut mozez dodac TYLKO 10 nowych tematów!'
				return render_to_response('errorek.html',{'blad':tekst, 'req':request})

			#straznike sprawadza czy nie sraka z przestworzy
			a = request.POST['tresc']
			if len(re.compile(u'\n').findall(a))*5>len(a) or len(re.compile(u'\n').findall(a))*5>40:
				tekst = u'Tutej nie srame'
				return render_to_response('errorek.html',{'blad':tekst, 'req':request})	
	
			#straznike sprawdza czy spam
			now = datetime.datetime.now()
			min=datetime.timedelta(minutes=10)
			for arch in Temat.objects.filter(data_pub__gt=now-min):
				if arch.tresc == request.POST['tresc'] or arch.tytul == request.POST['temat']:
					tekst = u'Wypupertalaj spamerze'
					return render_to_response('errorek.html',{'blad':tekst, 'req':request})	
		
			#obsluga tego calego bajzlu
			#obsluga autora
			if request.user.is_authenticated():
				#print 'raz'
				autor = request.user.get_profile()
			else:
				if Autor.objects.filter(pseudo=request.POST['autor']).count()==0:
					#print 'dwa'
					autor = Autor(pseudo=request.POST['autor'])
					autor.save()
				else:
					#print 'cztery'
					autor = Autor.objects.filter(pseudo=request.POST["autor"])[0]
			request.session['pomarancza'] = autor.pseudo

			#obsluga dresu
			addres = Adress(addres=request.META['REMOTE_ADDR'],
							autor=autor,
							data_wiz=datetime.datetime.now())
			addres.save()
			
			temat = Temat(autor=autor,
							data_pub=datetime.datetime.now(),
							tytul=request.POST['temat'],
							tresc=request.POST['tresc'],
							data_up=datetime.datetime.now())
			temat.save()
			
			return HttpResponseRedirect(reverse('forum.views.index', args=(0,)))
	else:
		try:
			serek = request.session['pomarancza']
		except:
			request.session['pomarancza'] = 'żywe gówno'
			serek = 'żywe gówno'
		
		if request.user.is_authenticated():
			form = NowyTemat(initial={'autor':request.user})
		else:
			form = NowyTemat(initial={'autor':request.session['pomarancza']})
		
	return render_to_response('nowytemat.html', {'form':form, 'req':request})
	
	
def rank(request):
	projekty = Autor.objects.filter(user__isnull=False).order_by('-rank')
	return render_to_response('rank.html', {'projekty':projekty, 'req':request})

def vote(request, wygrany, przegrany):

	#przezorny zawsze zabezpieczony
	try:
		if request.session['halt']:
			#czy kodełe z obrazka się zgadza?
			if request.POST['kod'].upper() != request.session['kod']:
				tekst = u'Złe kodełe z obrazka i tyle. Próbujesz ponownie'
				return render_to_response('errorek.html',{'blad':tekst})
			else:
				request.session['halt'] = False
				
		request.session['glosy'] +=1
		if request.session['glosy'] % 30 == 0:
			request.session['halt'] = True
			#print "raz dwa trzy teraz, jeszcze nie teraz", request.session['glosy'] % 3, request.session['glosy']
			return render_to_response('vote_lock.html',{'req':request})
	except:
		request.session['halt'] = True
		request.session['glosy'] =0
		return render_to_response('vote_lock.html',{'req':request})
	

			
	if wygrany != u'c' and przegrany != u'c':
		try:
			winer = Autor.objects.get(pk=request.session[wygrany])
			looser = Autor.objects.get(pk=request.session[przegrany])
			if winer != looser:
				
				winer.rank += 1
				looser.rank -= 1
				winer.save()
				looser.save()
				


		except:
			tekst = u'Nie majstrować'
			return render_to_response('errorek.html',{'blad':tekst})
	
	team = Autor.objects.\
				filter(user__isnull=False).\
				extra(select={
						'odp':'SELECT COUNT(*) FROM forum_odpowiedz WHERE forum_odpowiedz.autor_id=forum_autor.id',
						'tem':'SELECT COUNT(*) FROM forum_temat WHERE forum_temat.autor_id=forum_autor.id',
						})
	a = random.choice(team)
	b = random.choice(team)
	request.session['a'] = a.id
	request.session['b'] = b.id
	return render_to_response('vote.html', {'a':a, 'b':b, 'req':request})



def przyphaslo(request):
	if request.method == 'POST':

		#czy kodełe z obrazka się zgadza?
		if request.POST['kod'].upper() != request.session['kod']:
			tekst = u'Złe kodełe z obrazka i tyle. Próbujesz ponownie'
			return render_to_response('errorek.html',{'blad':tekst, 'req':request})



		form = PrzypHaslo(request.POST)
		if form.is_valid():
			pseudo = form.cleaned_data['pseudo']
			email  = form.cleaned_data['email']
			#print 'login: %s, email: %s'% (pseudo, email)

			try:
				zapominalski = Autor.objects.get(pseudo=pseudo, user__isnull=False)
			except:
				return render_to_response('przyphaslo.html', {'wiad':'Nie ma takiego loginu... buuu...'})

			#czy zapominalski zna swojego emaila?
			if not zapominalski.user.email == email: return render_to_response('przyphaslo.html',{'wiad':'Podałeś błędny adres email!'}) 
	
			#noweHaslo = "ALA"
			noweHaslo = ''.join([random.choice('ABCDEFGH') for i in range(10)])
			zapominalski.user.set_password(noweHaslo)
			zapominalski.user.save()
			zapominalski.save()
 
			send_mail('Twoje nowe hasło do forume żywych gówien', 'Twoje nowe hasło: %s'%noweHaslo, 'from@example.com', [zapominalski.user.email], fail_silently=False)
	
			return render_to_response('przyphaslo.html', {'thanks':True,})
	else:
		form = PrzypHaslo()

	return render_to_response('przyphaslo.html', {'form':form,})

